use redis::{AsyncCommands, Client};

// 设置值
pub async fn set(client: &Client, key: String, value: String) -> anyhow::Result<()> {
    let mut conn = client.get_async_connection().await?;
    conn.set(key, value).await?;
    Ok(())
}

pub async fn set_ex(
    client: &Client,
    key: String,
    value: String,
    seconds: usize,
) -> anyhow::Result<()> {
    let mut conn = client.get_async_connection().await?;
    conn.set_ex(key, value, seconds).await?;
    Ok(())
}

pub async fn del(client: &Client, key: &String) -> anyhow::Result<()> {
    let mut conn = client.get_async_connection().await?;
    conn.del(key).await?;
    Ok(())
}

// 获取值
pub async fn get(client: &Client, key: &String) -> anyhow::Result<String> {
    let mut conn = client.get_async_connection().await?;
    let value = conn.get(key).await?;
    Ok(value)
}

// 设置hash值
pub async fn hset(
    client: &Client,
    key: &String,
    field: String,
    value: String,
) -> anyhow::Result<()> {
    let mut conn = client.get_async_connection().await?;
    conn.hset(key, field, value).await?;
    Ok(())
}
// 获取hash值
pub async fn hget(client: &Client, key: &String, field: String) -> anyhow::Result<String> {
    let mut conn = client.get_async_connection().await?;
    let value = conn.hget(key, field).await?;
    Ok(value)
}
// 删除某个字段项
pub async fn hdel(client: &Client, key: &String, field: String) -> anyhow::Result<()> {
    let mut conn = client.get_async_connection().await?;
    conn.hdel(key, field).await?;
    Ok(())
}
// 从头部添加元素
pub async fn lpush(client: &Client, key: &String, value: String) -> anyhow::Result<()> {
    let mut conn = client.get_async_connection().await?;
    conn.lpush(key, value).await?;
    Ok(())
}

// 从尾部取出元素
pub async fn rpop(client: &Client, key: &String) -> anyhow::Result<String> {
    let mut conn = client.get_async_connection().await?;
    let value = conn.rpop(key, None).await?;
    Ok(value)
}
